<template>
  <div>
    <div v-if="!selectedItem.type">
      <slot />
    </div>
    <div v-else>
      <!-- 编辑器头部 -->
      <div class="header">
        <div class="info-title">{{ typeStr }}信息</div>
      </div>
      <!-- 实体编辑（文本展示） -->
      <div v-if="selectedItem.type === 'node'">
        <div style="display: flex; align-items: center; margin-bottom: 10px;">
          <div style="flex: 1; font-weight: bold;">实体名称:</div>
          <div style="flex: 2;">{{ selectedItem.item.name }}</div>
        </div>
        <div style="display: flex; align-items: center; margin-bottom: 10px;">
          <div style="flex: 1; font-weight: bold;">实体类别:</div>
          <div style="flex: 2;">{{ selectedItem.item.group }}</div>
        </div>
        <!-- 其他属性 -->
        <div
            v-for="(prop, idx) in selectedItem.item.properties"
            :key="idx"
            style="display: flex; align-items: center; margin-bottom: 10px;"
        >
          <div style="flex: 1; font-weight: bold;">{{ prop.name }}:</div>
          <div style="flex: 2; font-weight: normal; text-align: left;">
            {{ prop.value }}
          </div>
        </div>
        <div>
          <el-button
              v-if="!createNew && isAdmin()"
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="deleteItem"
          >删除</el-button>
          <el-button
              v-if="!createNew &&!editable && isAdmin()"
              size="small"
              type="primary"
              @click="openEditDialog"
          >修改</el-button>
<!--          <el-button-->
<!--            v-if="!createNew &&!editable && isAdmin()"-->
<!--            size="small"-->
<!--            type="info"-->
<!--            @click="openRiskDialog"-->
<!--          >风险设定</el-button>-->
        </div>
      </div>
      <!-- 关系编辑（文本展示） -->
      <div v-if="selectedItem.type === 'link'">
        <div style="display: flex; align-items: center; margin-bottom: 10px;">
          <div style="flex: 1; font-weight: bold;">关系实体 1:</div>
          <div style="flex: 2;">
            {{ getNodeName(selectedItem.item.from) }}
          </div>
        </div>
        <div style="display: flex; align-items: center; margin-bottom: 10px;">
          <div style="flex: 1; font-weight: bold;">关系实体 2:</div>
          <div style="flex: 2;">
            {{ getNodeName(selectedItem.item.to) }}
          </div>
        </div>
        <div style="display: flex; align-items: center; margin-bottom: 10px;">
          <div style="flex: 1; font-weight: bold;">关系名称:</div>
          <div style="flex: 2;">{{ selectedItem.item.name }}</div>
        </div>
        <div style="display: flex; align-items: center; margin-bottom: 10px;">
          <div style="flex: 1; font-weight: bold;">关系权重:</div>
          <div style="flex: 2;">{{ selectedItem.item.value }}</div>
        </div>
        <!-- 其他属性 -->
        <div
            v-for="(prop, idx) in selectedItem.item.properties"
            :key="idx"
            style="display: flex; align-items: center; margin-bottom: 10px;"
        >
          <div style="flex: 1; font-weight: bold;">{{ prop.name }}:</div>
          <div style="flex: 2; font-weight: normal; text-align: left;">
            {{ prop.value }}
          </div>
        </div>
        <div>
          <el-button
              v-if="!createNew && isAdmin()"
              size="small"
              type="danger"
              icon="el-icon-delete"
              @click="deleteItem"
          >删除</el-button>
          <el-button
              v-if="(!createNew &&!editable)"
              size="small"
              type="primary"
              @click="openEditDialog"
          >修改</el-button>
        </div>
      </div>
      <!-- 弹窗 -->
      <el-dialog
          :visible.sync="editDialogVisible"
          title="操作信息"
          @close="closeEditDialog"
      >
        <el-form
            ref="editForm"
            label-position="top"
            :rules="activeRules"
            :model="editItem"
            label-width="80px"
        >
          <!-- 实体编辑（弹窗内） -->
          <div v-if="selectedItem.type === 'node'">
            <!-- 实体名称 -->
            <el-form-item required prop="name">
              <div class="form-item-row">
                <label class="form-item-label">实体名称:</label>
                <el-input
                    clearable
                    placeholder="实体名称"
                    v-model="editItem.name"
                    class="custom-input"
                ></el-input>
              </div>
            </el-form-item>
            <!-- 实体类别 -->
            <el-form-item required prop="group">
              <div class="form-item-row">
                <label class="form-item-label">实体类别:</label>
                <el-autocomplete
                    clearable
                    :fetch-suggestions="queryGroup"
                    placeholder="实体类别"
                    v-model="editItem.group"
                    class="custom-input"
                ></el-autocomplete>
              </div>
            </el-form-item>
            <!-- 实体权重 -->
            <el-form-item required prop="radius">
              <div class="form-item-row">
                <label class="form-item-label">实体权重:</label>
                <el-input
                    clearable
                    placeholder="1~20"
                    v-model.number="editItem.radius"
                    class="custom-input"
                ></el-input>
              </div>
            </el-form-item>
            <!-- 实体颜色 -->
            <el-form-item>
              <div class="form-item-row">
                <label class="form-item-label">实体颜色:</label>
                <div class="radio-and-color-container">
                  <el-radio-group v-model="editUseGroupColor">
                    <el-radio :label="true" style="margin-bottom: 10px">按默认分组颜色</el-radio>
                    <el-radio :label="false">按照自定义颜色</el-radio>
                  </el-radio-group>
                  <el-input
                      style="padding-top: 10px"
                      v-if="!editUseGroupColor"
                      type="color"
                      v-model="editItem.color"
                      class="custom-input"
                  ></el-input>
                </div>
              </div>
            </el-form-item>
            <!-- 字体大小 -->
            <el-form-item required prop="textSize">
              <div class="form-item-row">
                <label class="form-item-label">字体大小:</label>
                <el-input
                    clearable
                    placeholder="单位 px (建议为 15)"
                    v-model.number="editItem.textSize"
                    class="custom-input"
                ></el-input>
              </div>
            </el-form-item>
            <!-- 其他属性 -->
            <el-form-item>
              <div
                  v-for="(prop, idx) in editItem.properties"
                  :key="idx"
                  class="property-row"
              >
                <el-autocomplete
                    clearable
                    :fetch-suggestions="queryAttributes"
                    placeholder="属性名"
                    v-model="prop.name"
                    class="property-input"
                />
                <el-input
                    clearable
                    type="textarea"
                    :autosize="{ maxRows: '5' }"
                    placeholder="属性值"
                    v-model="prop.value"
                    class="property-input"
                />
                <el-button
                    type="danger"
                    icon="el-icon-close"
                    @click="removeProp(idx)"
                    class="delete-button"
                />
              </div>
              <el-button icon="el-icon-plus" @click="addProp" class="add-button">添加属性</el-button>
            </el-form-item>
          </div>
          <!-- 关系编辑（弹窗内） -->
          <div v-if="selectedItem.type === 'link'">
            <!-- 关系实体 1 -->
            <el-form-item required prop="from">
              <div style="display: flex; align-items: center;">
                <div style="flex: 1; font-weight: bold;">关系实体 1:</div>
                <div style="flex: 2; display: flex; align-items: center;">
                  <el-autocomplete
                      style="width: 300px"
                      clearable
                      placeholder="实体名称"
                      :fetch-suggestions="queryNodeOptions"
                      v-model="editItem.from"
                      @select="handleNodeSelect('from', $event)"
                      value-key="label"
                      label="label"
                      :disabled="isEditMode"
                  ></el-autocomplete>
                </div>
              </div>
            </el-form-item>
            <!-- 关系实体 2 -->
            <el-form-item required prop="to">
              <div style="display: flex; align-items: center;">
                <div style="flex: 1; font-weight: bold;">关系实体 2:</div>
                <div style="flex: 2; display: flex; align-items: center;">
                  <el-autocomplete
                      clearable
                      placeholder="实体名称"
                      v-model="editItem.to"
                      style="width: 300px"
                      :fetch-suggestions="queryNodeOptions"
                      @select="handleNodeSelect('to', $event)"
                      value-key="label"
                      label="label"
                      :disabled="isEditMode"
                  ></el-autocomplete>
                </div>
              </div>
            </el-form-item>
            <!-- 关系名称 -->
            <el-form-item required prop="name">
              <div style="display: flex; align-items: center;">
                <div style="flex: 1; font-weight: bold;">关系名称:</div>
                <div style="flex: 2;">
                  <el-autocomplete
                      clearable
                      style="width: 300px"
                      :fetch-suggestions="queryLinkName"
                      placeholder="关系名称"
                      v-model="editItem.name"
                  ></el-autocomplete>
                </div>
              </div>
            </el-form-item>
            <!-- 关系权重 -->
            <el-form-item required prop="value">
              <div style="display: flex; align-items: center;">
                <div style="flex: 1; font-weight: bold;">关系权重:</div>
                <div style="flex: 2;">
                  <el-input
                      clearable
                      style="width: 300px"
                      placeholder="1~20"
                      v-model="editItem.value"
                  ></el-input>
                </div>
              </div>
            </el-form-item>
            <!-- 其他属性 -->
            <el-form-item>
              <div
                  v-for="(prop, idx) in editItem.properties"
                  :key="idx"
                  class="property-row"
                  style="display: flex; align-items: center; margin-bottom: 10px;"
              >
                <el-autocomplete
                    clearable
                    :fetch-suggestions="queryAttributes"
                    placeholder="属性名"
                    v-model="prop.name"
                    style="flex: 1; margin-right: 10px;"
                />
                <el-input
                    clearable
                    type="textarea"
                    :autosize="{ maxRows: '5' }"
                    placeholder="属性值"
                    v-model="prop.value"
                    style="flex: 2; margin-right: 10px;"
                />
                <el-button
                    type="danger"
                    icon="el-icon-close"
                    @click="removeProp(idx)"
                    style="width: 24px; height: 24px; padding: 0; line-height: 24px; text-align: center; font-size: 12px;"
                />
              </div>
              <el-button icon="el-icon-plus" @click="addProp">添加属性</el-button>
            </el-form-item>
          </div>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeEditDialog">取消</el-button>
            <el-button type="primary" @click="saveEdit">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import { deepCopy } from '../../../common/utils/object'
export default {
  name: 'GraphEditorItem',
  props: {
    projectId: {
      type: Number
    },
    nodeOptions: {
      type: Array
    },
    nodeGroups: {
      type: Array
    }
  },
  data() {
    return {
      isEditMode: false, // 判断是添加信息，还是修改信息
      editorTitle: '',
      useGroupColor: false,
      editable: false,
      projectInfo: {
        id: null
      },
      selectedItem: {
        type: null,
        item: {}
      },
      originItem: null,
      options: {
        nodeOptions: [],
        nodeGroups: [],
        itemGroups: [],
        linkNames: [],
        nodeProperties: {

        },
        linkProperties: {

        }
      },
      selectingNode: '',
      selectingMode: false,
      rules: {
        node: {
          name: [{ required: true, message: '实体名称为必填项' }],
          group: [{ required: true, message: '实体类别为必填项' }],
          radius: [
            { required: true, message: '实体权重为必填项' },
            { type: 'number', min: 1, message: '实体权重必须为正整数' }
          ],
        },
        link: {
          name: [{ required: true, message: '关系名称为必填项' }],
          fromId: [{ required: true, message: '关系实体1必须从下拉列表选择' }],
          toId: [{ required: true, message: '关系实体2必须从下拉列表选择' }],
          value: [{ required: true, message: '关系权重为必填项' }]
        }
      },
      editDialogVisible: false,
      riskDialogVisible: false,
      editItem: {
        from: '',   // 显示名称
        fromId: '', // 实际ID
        to: '',
        toId: '',
        name: ''
      },
      editUseGroupColor: false
    }
  },
  computed: {
    typeStr() {
      return this.selectedItem.type === 'node'? '实体' : '关系'
    },
    editorTitle() {
      return this.createNew
          ? `新增${this.typeStr}`
          : `${this.typeStr} ID: ${this.selectedItem.item.id}`
    },
    createNew() {
      return!this.selectedItem.item.id
    },
    primaryButton() {
      return!this.createNew
          ? this.editable
              ? { label: `确认修改`, handler: this.updateItem }
              : {
                label: '点击修改',
                handler: () => {
                  this.editable = true
                  // 遍历节点的其他属性，将 isEditing 设为 true
                  if (this.selectedItem.type === 'node') {
                    this.selectedItem.item.properties.forEach(prop => {
                      prop.isEditing = true;
                    });
                  }
                  // 遍历关系的其他属性，将 isEditing 设为 true
                  if (this.selectedItem.type === 'link') {
                    this.selectedItem.item.properties.forEach(prop => {
                      prop.isEditing = true;
                    });
                  }
                }
              }
          : { label: `新增${this.typeStr}`, handler: this.createItem }
    },
    alterButton() {
      return this.createNew
          ? { label: '重置选项', handler: this.reset }
          : { label: '取消修改', handler: this.cancel }
    },
    activeRules() {
      return this.rules[this.selectedItem.type]
    }
  },
  watch: {
    projectId(id) {
      this.projectInfo.id = id
    },
    useGroupColor(bool) {
      if (bool) {
        this.selectedItem.item.color = ''
      }
    },
    nodeOptions(options) {
      this.options.nodeOptions = options
    },
    nodeGroups(groups) {
      this.options.nodeGroups = groups
    }
  },
  methods: {
    ...mapActions({
      createItemAct: 'createItem',
      updateItemAct: 'updateItem',
      deleteItemAct: 'deleteItem'
    }),
    // 判断角色是否是管理员
    isAdmin() {
      return this.$store.getters.role === 'ADMIN' || localStorage.getItem('user-role') === 'ADMIN';
    },

    // 用于处理节点选择事件
    handleNodeSelect(field, selectedItem) {
      console.log('选中的实体:', selectedItem); // 调试看看选中的数据结构
      this.editItem[field] = selectedItem.label;   // 输入框显示 name
      this.editItem[`${field}Id`] = selectedItem.value; // 额外存 ID
    },
    // 模糊匹配
    queryNodeOptions(queryString, cb) {
      const results = this.options.nodeOptions.filter(node => {
        return node.name.toLowerCase().includes(queryString.toLowerCase());
      });
      cb(results.map(node => ({
        value: node.id,  // 这里是 id
        label: node.name  // 这里是 name
      })));
    },
    /********** 外部操作事件 **********/
    createNode() {
      const newNode = this.getEditNode()
      // console.log('createNode')

      this.selectedItem.type = 'node'
      this.selectedItem.item = newNode
      this.originItem = null
      this.editable = true
      this.useGroupColor = true
      this.$emit('graph-action', 'clearFocus')
      // 打开修改实体的弹窗
      this.openEditDialog();
    },
    createLink() {
      const newLink = this.getEditLink()
      // console.log('createLink')

      this.selectedItem.type = 'link'
      this.selectedItem.item = newLink
      this.originItem = null
      this.editable = true
      this.useGroupColor = true
      this.$emit('graph-action', 'clearFocus')
      // 打开修改实体的弹窗
      console.log('创建节点：',this.editItem)
      this.openEditDialog();
    },
    selectNode(node) {
      const newNode = this.getEditNode(node)
      // console.log('selectNode', newNode)

      this.selectedItem.type = 'node'
      this.selectedItem.item = newNode
      this.originItem = deepCopy(newNode)
      this.editable = false
      this.useGroupColor =!node.color
    },
    selectLink(link) {
      const newLink = this.getEditLink(link)
      // console.log('selectLink', link)

      this.selectedItem.type = 'link'
      this.selectedItem.item = newLink
      this.originItem = deepCopy(newLink)
      this.editable = false
      this.useGroupColor = true
    },
    selectNone() {
      // console.log('selectNone')
      this.selectedItem.type = ''
      this.selectedItem.item = {}
      this.$emit('graph-action', 'clearFocus')
    },
    /********** 内部方法 **********/
    getEditNode(origin) {
      if (origin) {
        const {
          id,
          name,
          group,
          radius,
          color,
          figure,
          textSize,
          properties
        } = origin
        const props = []
        for (const name in properties) {
          props.push({ name, value: properties[name] })
        }
        const node = {
          id,
          name,
          group,
          radius,
          color,
          figure,
          textSize,
          properties: props
        }
        return node
      } else {
        return {
          name: '',
          group: '',
          radius: '',
          color: '',
          figure: '',
          textSize: '',
          properties: []
        }
      }
    },
    getEditLink(origin) {
      if (origin) {
        const { id, name, from, to, value, properties } = origin
        const props = []
        for (const name in properties) {
          props.push({ name, value: properties[name] })
        }
        const newLink = { id, name, from, to, value, properties: props }
        return newLink
      } else {
        return {
          name: '',
          from: '',
          to: '',
          value: '',
          properties: []
        }
      }
    },
    // 切换属性项的编辑模式
    toggleEditMode(prop) {
      prop.isEditing =!prop.isEditing;
    },
    // 添加属性方法
    addProp() {
      this.editItem.properties.push({ name: '', value: '', isEditing: true });
    },
    // 删除实体属性
    removeProp(idx) {
      this.editItem.properties.splice(idx, 1)
    },
    toggleSelectingNode(attr) {
      const mode = this.selectingNode!== attr
      const node = mode? attr : ''
      this.selectingMode = mode
      this.selectingNode = node
      this.$emit('graph-action', 'setSelectingMode', mode)
    },
    catchNode(node) {
      const { id, name } = node
      // console.log(`catchNode: id=${id}, name=${name}`)
      this.selectedItem.item[this.selectingNode] = node.id
      this.selectingMode = false
      this.selectingNode = ''
    },
    // 重置选项
    reset() {
      const item = this.selectedItem.item
      for (const prop in item) {
        item[prop] = ''
      }
    },
    // 重置属性
    cancel() {
      this.editable = false
      // reset attribute
      this.selectedItem.item = deepCopy(this.originItem)
    },
    validate() {
      return new Promise(resolve => {
        this.$refs.editForm.validate(res => {
          resolve(res)
        })
      })
    },
    async createItem() {
      const {
        projectInfo: { id: projectId },
        selectedItem: { type, item },
        validate
      } = this
      const res = await validate()
      console.log('validate', res)
      if (!res) return
      let payload = { ...item };

      if (type === 'link') {
        // link 需要提交真实 ID
        payload = {
          ...payload,
          from: item.fromId, // 使用真实 ID
          to: item.toId
        };
      }
      this.createItemAct({ projectId, type, item:payload }).then(item => {
        if (item) {
          if (type === 'node') {
            this.$emit('graph-action', 'createNode', item)
            this.selectNode(item)
          } else if (type === 'link') {
            this.$emit('graph-action', 'createLink', item)
            this.selectLink(item)
          }
        }
      })
    },
    async updateItem() {
      const {
        projectInfo: { id: projectId },
        selectedItem: { type, item },
        validate
      } = this
      const res = await validate()
      console.log('validate', this.selectedItem.item)
      if (!res) return
      this.updateItemAct({ projectId, type, item: this.selectedItem.item }).then(item => {
        if (item) {
          if (type === 'node') {
            this.$emit('graph-action', 'updateNode', item)
            this.selectNode(item)
          } else if (type === 'link') {
            this.$emit('graph-action', 'updateLink', item)
            this.selectLink(item)
          }
        }
      })
    },
    deleteItem() {
      const {
        projectInfo: { id: projectId },
        selectedItem: { type, item }
      } = this
      console.log('deleteItem', this.projectId)
      this.deleteItemAct({ projectId:this.projectId, type, id: item.id }).then(res => {
        if (res) {
          const action =
              type === 'node'? 'deleteNode' : type === 'link'? 'deleteLink' : ''
          if (action) {
            this.$emit('graph-action', action, item.id)
            this.selectNone()
          }
        }
      })
    },
    queryGroup(_, cb) {
      return cb(this.options.itemGroups.map(group => ({ value: group })))
    },
    queryLinkName(_, cb) {
      return cb(this.options.linkNames.map(name => ({ value: name })))
    },
    queryAttributes(_, cb) {
      const {
        selectedItem: {
          type,
          item: { name, group }
        },
        options: { nodeProperties, linkProperties }
      } = this
      const prop = type === 'node'? group : name
      const props = type === 'node'? nodeProperties : linkProperties
      const suggestions = props[prop] || []
      return cb(suggestions.map(option => ({ value: option })))
    },
    // 风险弹窗
    openRiskDialog(){
      this.riskDialogVisible = true;
    },
    openEditDialog() {
      this.editItem = deepCopy(this.selectedItem.item);
      this.editUseGroupColor = this.useGroupColor;
      this.editDialogVisible = true;
      if (this.createNew) {
        // 新增操作
        this.isEditMode = false;
      } else {
        // 修改操作
        this.isEditMode = true;
      }
    },
    closeEditDialog() {
      this.editItem = {};
      this.editDialogVisible = false;
    },
    async saveEdit() {
      const res = await this.validate();
      if (!res) return;
      // 将 editItem 的值同步到 selectedItem.item
      this.selectedItem.item = deepCopy(this.editItem);
      if (this.createNew) {
        // 新增操作
        this.createItem();
      } else {
        // 修改操作
        this.updateItem();
      }
      this.closeEditDialog();
    },
    getNodeName(nodeId) {
      const node = this.options.nodeOptions.find(node => node.id === nodeId);
      return node? node.name : '';
    }
  }
}
</script>
<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header > .left {
  display: flex;
  gap: 16px;
}

.properties {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}

.properties > .name {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.properties + .properties {
  margin-top: 10px;
}
.info-title{
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

/* 弹窗样式 */
.form-item-row {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.form-item-label {
  font-weight: bold;
  margin-right: 10px;
  width: 80px;
}

.custom-input {
  width: 200px;
}

.radio-and-color-container {
  display: flex;
  flex-direction: column;
}

.property-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.property-input {
  margin-right: 10px;
  flex: 1;
  width: 200px;
}

.delete-button {
  width: 24px;
  height: 24px;
  padding: 0;
  line-height: 24px;
  text-align: center;
  font-size: 12px;
}

.add-button {
  margin-top: 10px;
}
</style>
